package com.teamtgv.shareshark;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
 
public class JSONParser {
 
    private InputStream is = null;
    private JSONObject jObj = null;
    private String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
    	
    	Log.v("JSON Parser", "Making request for " + url);
 
    	HttpParams httpParams = new BasicHttpParams();
    	HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
   	 
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
        
        // Making HTTP request
        try {
 
            // check for request method
            if(method == "POST"){
                // request method is POST
            	HttpPost httpPost = new HttpPost(url);
            	httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                if (httpPost.isAborted())
                	Log.v("JSON Parser", "POST is aborted");

                HttpEntity responseEntity = httpResponse.getEntity();
                if (responseEntity.getContentType() != null)
                	Log.v("JSON Parser", "HTTP response content type: " + responseEntity.getContentType().getName() + " - " + responseEntity.getContentType().getValue());
                
                Log.v("JSON Parser", "sent POST request");
                
                is = responseEntity.getContent();
                
                // Read POST request headers
                InputStream requestis = httpPost.getEntity().getContent();
                BufferedReader requestReader = new BufferedReader(new InputStreamReader(requestis), 65728);
                StringBuilder requestStringBuilder = new StringBuilder();
                String line = null;
                while ((line = requestReader.readLine()) != null) {
                	requestStringBuilder.append(line + "\n");
                }
                requestis.close();
                Log.v("JSON Parser", "HTTP POST request: " + requestStringBuilder.toString());
                
                // end reading headers
                Log.v("JSON Parser", "response length: " + responseEntity.getContentLength());  //it should not be 0
            }else if(method == "GET"){
                // request method is GET
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
 
                Log.v("JSON Parser", "sent get request");
                is = httpEntity.getContent();
            }           
 
        } catch (Exception e) {
            e.printStackTrace();
            Log.v("JSON Parser", "Error while performing HTTP request");
            Log.v("JSON Parser", e.toString() + ": " + e.getMessage());
        }
        
       
 
        try {
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is), 65728);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
            	Log.v("JSON Parser", "read response line: " + line);
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.v("JSONParser", "Response from JSON: " + json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}